﻿using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text;
using Microsoft.AspNetCore.Http;
using System.Net;
using System;
using ServiceStack.Host;
using Newtonsoft.Json;
using static ServiceStack.Diagnostics.Events;
using ServiceStack.Web;
using ServiceStack;
using System.Collections.Generic;
using ServiceStack.Script;
using System.Runtime.Intrinsics.X86;
using Nancy.Json;
using static ServiceStack.Svg;
using Newtonsoft.Json.Linq;
using System.Web.Http.Results;
using Nancy;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace studydemo.Controllers
{
    [Produces("application/json")]
    [Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
    [ApiController]
    public class BydController : ControllerBase

    {

        public BydController() { }
        // GET: api/<BydController>
        /// <summary>
        /// 查找全部物料
        /// </summary>
        /// <returns></returns>
        [Produces("application/json")]
        //[Produces("text/json")]
        [HttpGet]
        public async Task<string> GetAsync( )
        {
            using (var httpClient = new System.Net.Http.HttpClient())
            {
                var username = "ANNIE.P";
                var password = "Annie.p2024*123";

                var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                var url = "https://my424803.businessbydesign.cloud.sap/sap/byd/odata/cust/v1/kfcustomerinvoicerequest/CustomerInvoiceRequestCollection?$format=json&$expand=Item,PaymentControl/PaymentControlExternalPayment&$filter=BaseBusinessTransactionDocumentID eq '4236'";

                //发送请求
                var result = await httpClient.GetAsync(url);

                //_responseCookies = Cookies.GetCookies(url).Cast<Cookie>();
                if (result.IsSuccessStatusCode)
                {
                    var content = await result.Content.ReadAsStringAsync();
                    //字符串转化为json对象
                    JObject jo = JObject.Parse(content);
                    Console.WriteLine(content);
                    return content;

                }
                else
                {
                    Console.WriteLine("Error: " + result.StatusCode);
                }

            }
            return "new JObject()";
            
        }

        // GET api/<BydController>/5
        /// <summary>
        /// 查找物料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<string> GetAsync(string id)
        {
            using (var httpClient = new System.Net.Http.HttpClient())
            {

                var username = "ANNIE.P";
                var password = "Annie.p2024*123";
                var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                var url = $"https://my424803.businessbydesign.cloud.sap/sap/byd/odata/cust/v1/kfmaterial/MaterialCollection?$format=json&$expand=MaterialDescription,QuantityConversion,QuantityCharacteristic,Purchasing,Sales&$select=MaterialDescription/ObjectID,MaterialDescription/DescriptionLanguageCode,QuantityConversion,QuantityCharacteristic/ObjectID,QuantityCharacteristic/CharacteristicQuantityTypeCode,Purchasing/ObjectID,Sales/ObjectID,Sales/SalesOrganisationID&$filter=InternalID eq {id}";
                var result = await httpClient.GetAsync(url);

                if (result.IsSuccessStatusCode)
                {
                    var content = await result.Content.ReadAsStringAsync();
                    return content;
                }
                else
                {
                    Console.WriteLine("Error: " + result.StatusCode);
                }
            }
            return "value";
        }

        /// <summary>
        /// 创建物料
        /// </summary>
        [HttpPost("postname")]
        public async Task<string> PostAsync(dynamic body)
        {
            var url = "https://my424803.businessbydesign.cloud.sap/sap/byd/odata/cust/v1/kfcustomerinvoicerequest/CustomerInvoiceRequestCollection?$format=json&$expand=Item,PaymentControl/PaymentControlExternalPayment&$filter=BaseBusinessTransactionDocumentID eq '4236'";
            StringBuilder sb_cookie = new StringBuilder();
            CookieContainer cookieContainer = new CookieContainer();
            var uri = new Uri(url);
            var handler = new HttpClientHandler();
            handler.CookieContainer = cookieContainer;

            using (var httpClient = new System.Net.Http.HttpClient(handler))
            {
                var username = "ANNIE.P";
                var password = "Annie.p2024*123";
                var _url = "https://my424803.businessbydesign.cloud.sap/sap/byd/odata/cust/v1/kfmaterial/MaterialCollection";
                var _uri = new Uri(_url);
                var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
                //发送fetch
                httpClient.DefaultRequestHeaders.Add("X-CSRF-TOKEN", "fetch");

                //发送请求
                var result = await httpClient.GetAsync(url);

                List<Cookie> cookies = cookieContainer.GetCookies(uri).Cast<Cookie>().ToList();
                foreach (var item in cookies)
                {
                    sb_cookie.Append(item.Name);
                    sb_cookie.Append("=");
                    sb_cookie.Append(item.Value);
                    sb_cookie.Append(";");

                }
                var result_cookie = sb_cookie.ToString();
                Console.WriteLine("result_cookie: " + result_cookie);
                foreach (var cookie in cookies)
                {
                    cookieContainer.Add(new Uri(_url), cookie);
                }
                //获取csrf令牌
                String csrfToken = result.Headers.GetValues("X-CSRF-TOKEN").FirstOrDefault();
                Console.WriteLine("result: " + result);

                var handler1 = new HttpClientHandler() { CookieContainer = cookieContainer };
                //发送post请求
                string payloadJson;
                string jsonResponse;
                HttpResponseMessage response;//发送请求
                HttpContent content;
                var httpClient1 = new System.Net.Http.HttpClient(handler1) { };


                //发送post body
                //把json对象转化为字符串
                payloadJson = System.Text.Json.JsonSerializer.Serialize(body);

                content = new StringContent(payloadJson);

                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                httpClient1.DefaultRequestHeaders.Add("x-csrf-token", csrfToken);
                httpClient1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
                Console.WriteLine("body:" + body);
                Console.WriteLine("payloadJson:" + payloadJson);
                try
                { 
                     response = await httpClient1.PostAsync(_uri, content);
                    Console.WriteLine("response: " + response);
                    if (response.IsSuccessStatusCode)
                    {
                        jsonResponse = await response.Content.ReadAsStringAsync();
                        return "发送成功";
                        return jsonResponse;
                        //do something with json response here                    
                    }
                     else
                    {
                        Console.WriteLine("jsonResponse1: " + await response.Content.ReadAsStringAsync());
                        return "发送失败";
                    }

                }
                catch (Exception e)
                {
                    string error = e.GetBaseException().ToString();
                    //Could not connect to server
                    return error;
                }

            }

        }



    }
}
